package com.cskaoyan.market.controller;

import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.annotation.MultipartConfig;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;

@WebServlet("/storage/*")
@MultipartConfig
public class AdminStorageImage extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String requestURI = req.getRequestURI();
        // /wx/storage/fetch/1f7600dc-81b0-41bf-a19e-dc0b8a4a806b-1.png
        String key = requestURI.replace(req.getContextPath() + "/storage/", "");
        //应该去到d:image目录中去查找该文件
        String path = "D:/image";
        File file = new File(path + "/" + key);
        if(file.exists() && file.isFile()){
            //文件存在且不是目录，响应出去
            FileInputStream fileInputStream = new FileInputStream(file);
            ServletOutputStream outputStream = resp.getOutputStream();
            int length = 0;
            byte[] bytes = new byte[1024];
            while ((length = fileInputStream.read(bytes)) != -1) {
                outputStream.write(bytes, 0, length);
            }
            return;
        }
        resp.sendError(404);
    }
}
